import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import base from "@src/store/base";
import location from "@src/store/location";
import router from "@src/router";
import { getAppointmentShopDetail } from "@src/api/reservation";
import { OPEN_STATE_TEXT } from "@src/sp-reservation/constant/index.js";

Component({
  behaviors: [storeBindingsBehavior, router.routerBehavior],
  storeBindings: [
    {
      store: base,
      fields: ["themeColor", "themeTitleColor", "perms"],
    },
    {
      store: location,
      fields: ["latitude", "longitude"],
      actions: ["getLocation"],
    },
  ],
  data: {
    shopId: null,
    navIndex: 2,
    OPEN_STATE_TEXT,
    scrollTop: 0,
    isShowAllNotice: false,
    introductionHeight: 0,
    shopDescriptions: [],
  },
  observers: {},
  methods: {
    onLoad(options) {
      if (options.navIndex) {
        this.setData({
          shopId: options.shopId,
          navIndex: Number(options.navIndex),
        });
      } else {
        this.setData({ shopId: options.shopId, navIndex: 2 });
      }
    },
    onLogin() {
      this.getLocation(true)
        .then((res) => {
          if (this.data.shopId) {
            this.setData({ latitude: res.latitude, longitude: res.longitude });
            this.fetchData();
          }
        })
        .catch((res) => {
          if (this.data.shopId) {
            this.fetchData();
          }
        });
    },
    onClickShowNotice() {
      this.setData({
        isShowAllNotice: !this.data.isShowAllNotice,
      });
    },
    setIntroductionHeight() {
      const _self = this;
      //创建节点选择器
      const query = wx.createSelectorQuery();
      //选择id
      query.selectAll("#introduction1").boundingClientRect(function (rect) {
        _self.setData({
          introductionHeight: _self.data.introductionHeight + rect[0].height,
        });
      });
      query.selectAll("#introduction2").boundingClientRect(function (rect) {
        _self.setData({
          introductionHeight: _self.data.introductionHeight + rect[0].height,
        });
      });
      query.exec();
    },
    handleChange(e) {
      //1是设施，2是介绍
      const navIndex = e.currentTarget.dataset.index;
      this.setData({ navIndex });
      //当navIndex===2的时候，整体shopDetail 的滚动高度回归到0
      //当navIndex === 1的时候，整体shopDetail 的 滚动高度是shop-introduction的高度的加外边距
      this.setData({
        scrollTop: navIndex === 1 ? this.data.introductionHeight : 0,
      });
    },
    handleOnScroll(e) {
      const { scrollTop } = e.detail;
      this.setData({
        navIndex: scrollTop > this.data.introductionHeight - 10 ? 1 : 2,
      });
      // console.log("scrollTop", scrollTop, this.data.introductionHeight);
    },
    fetchData: function () {
      let data = {
        latitude: this.data.latitude ? this.data.latitude : "",
        longitude: this.data.longitude ? this.data.longitude : "",
        shopId: this.data.shopId,
      };
      return getAppointmentShopDetail(data).then((res) => {
        if (res.code === 0) {
          let data = { ...res.data };
          let supplyService = this.parseStr(data.supplyService);
          let supplyFacility = this.parseStr(data.supplyFacility);

          let supplyFacilityCheckListArr = [];
          let supplyServiceCheckListArr = [];
          let customerCheckListArr = [];
          if (supplyService) {
            supplyService.forEach((item) => {
              if (item.checkList.length > 0) {
                if (item.label === "其它服务") {
                  customerCheckListArr.push(...item.checkList);
                } else {
                  supplyServiceCheckListArr.push(...item.checkList);
                }
              }
            });
          }
          if (supplyFacility) {
            supplyFacility.forEach((item) => {
              if (item.checkList.length > 0) {
                if (item.label === "其它设施") {
                  customerCheckListArr.push(...item.checkList);
                } else {
                  supplyFacilityCheckListArr.push(...item.checkList);
                }
              }
            });
          }
          let shopInfo = data;
          if (shopInfo && shopInfo.shopInfoResp.distance) {
            shopInfo.distance = (
              (shopInfo.shopInfoResp.distance || 0) / 1000
            ).toFixed(2);
          }
          let shopDescriptions = [];
          if (data.description) {
            data.description.split(";").map((v) => {
              if (v.trim()) {
                shopDescriptions.push(v);
              }
            });
          }
          this.setData({
            shopInfo: shopInfo,
            imageList: data.imageList,
            description: data.shopInfoResp.description,
            shopDescriptions: shopDescriptions,
            supplyFacilityCheckListArr: supplyFacilityCheckListArr,
            supplyServiceCheckListArr: supplyServiceCheckListArr,
            customerCheckListArr: customerCheckListArr,
            supplyService: supplyService,
          });
          this.setIntroductionHeight();
        }
      });
    },
    handleOpenMap(e) {
      let data = e.currentTarget.dataset.item;
      wx.openLocation({
        latitude: data.latitude,
        longitude: data.longitude,
        name: data.name,
        address: data.address,
      });
    },
    callPhone(e) {
      if (!e.currentTarget.dataset.phone) {
        wx.showToast({ title: "该店铺暂未设置客服电话", icon: "none" });
        return;
      }
      console.log(e);
      wx.makePhoneCall({
        phoneNumber: e.currentTarget.dataset.phone, //仅为示例，并非真实的电话号码
      });
    },
    parseStr(jsonStr) {
      if (!jsonStr) {
        return null;
      }
      try {
        return JSON.parse(jsonStr);
      } catch (e) {
        console.info("解析异常", e, jsonStr);
      }
      return null;
    },
  },
});
